import { asyncRoutes } from '@/router'
import { constantRoutes } from '@/router'
import { removeRoutes } from '../../router'
import { handleRoutesSort } from '../../utils/route'

/**
 *  判断是否用用权限
 * 返回true表示拥有权限
 * @param roles
 * @param route
 * @returns
 */
const hasPermission = (roles, route) => {
  // 如果meta不存在 或者roles不存在，则表示拥有任何权限
  if (!route.meta || !Array.isArray(route.meta.roles)) return true

  return roles.some((role) => route.meta?.roles?.includes(role))
}

/**
 * 过滤路由
 * @param asyncRoutes 所有的动态路由
 * @param roles  角色 [common, admin]
 * @returns
 */
const filterAsyncRoutes = (asyncRoutes, roles) => {
  const res = []
  asyncRoutes.forEach((route) => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children && r.children.length > 0) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })

  return res
}

export default {
  namespaced: true,
  state: {
    // 全部路由
    routes: [],

    // 动态路由 -> 侧边栏路由
    dynamicRoutes: []
  },
  mutations: {
    SET_ROUTES(state, routes) {
      state.routes = constantRoutes.concat(routes)
      state.dynamicRoutes = routes
    },
    RESET_ROUTES(state) {
      state.routes = []
      state.dynamicRoutes = []
    }
  },
  actions: {
    setRoutes({ commit }, roles) {
      return new Promise((resolve) => {
        handleRoutesSort(asyncRoutes) // 进行路由排序处理
        let accessedRoutes = []
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
        return accessedRoutes
      })
    },
    resetRoutes({ commit }) {
      commit('RESET_ROUTES')
      removeRoutes()
    }
  }
}
